package com.oceansoft.mobile.econsole.modules.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.encrypt.DESUtil;
import com.oceansoft.mobile.econsole.common.util.encrypt.DesAPPUtils;
import com.oceansoft.mobile.econsole.modules.api.entity.DriverInfos;
import com.oceansoft.mobile.econsole.modules.api.persistence.IDriverInfoMapper;
import com.oceansoft.mobile.econsole.modules.api.service.IQueryService;
import com.oceansoft.mobile.econsole.modules.api.util.UserInfoUtil;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMemberMange;
import com.oceansoft.mobile.econsole.modules.member.persistence.IWtMemberMapper;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory;
import com.oceansoft.mobile.econsole.modules.weixin.service.WeixinQueryService;
import com.oceansoft.mobile.econsole.weixin.api.OauthAPI;
import com.oceansoft.mobile.econsole.weixin.api.enums.OauthScope;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory.HOST;
import static com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory.SYHOST;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 查询办事
 *
 * @author jin.xu
 * @createTime 2015年4月13日 下午2:18:53
 * @packagePath com.oceansoft.mobile.econsole.modules.weixin.controller.MatterQueryController.java
 */
@Controller
@RequestMapping("weixin/wx_member")
public class UserProfileController extends BaseController {


    private static final Logger log = LoggerFactory.getLogger(BaseController.class);
    @Resource
    private IDriverInfoMapper driverInfoMapper;
    @Resource
    private IMemberService memberService;
    @Resource
    private WeixinQueryService weixinQueryService;

    /**
     * 微信端进入微信首页oauth认证
     */
    @RequestMapping(value = "oauth", method = GET)
    public String gotoWxMemberOAuth(HttpServletRequest request) {
        OauthAPI oauthAPI = WxFactory.buildOauthAPI();
        return "redirect:" + oauthAPI.getOauthPageUrl(WxFactory.MEMBER_OAUTH_URL, OauthScope.SNSAPI_BASE, "123");
    }

    /**
     * 基础认证方法，获取code，为了获取用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "baseOauth", method = GET)
    public String gotoAuth(HttpServletRequest request) {
        OauthAPI oauthAPI = WxFactory.buildOauthAPI();
        String url = request.getParameter("url");
        Preconditions.checkNotNull(url, "参数不能为空！！");
        return "redirect:" + oauthAPI.getOauthPageUrl(url, OauthScope.SNSAPI_BASE, "123");
    }

    /**
     * 手机APP集成微信首页跳转链接
     *
     * @param request
     * @return
     */
    /*@RequestMapping(value = "toIndex", method = GET)
    public String gotoWeixinIndexPre(HttpServletRequest request) {
        return "weixin/pre_index";
    }*/

    /**
     * 微信首页
     */
    @RequestMapping(value = "index", method = GET)
    public String gotoWeixinIndex(HttpServletRequest request, Model model) throws Exception {

        String openId = super.getOpenId(request);
        WtMember member = getWxMemberSession();
        model.addAttribute("member", member);
        model.addAttribute("openId", openId);
        model.addAttribute("productUrl", configInfo.getServiceInterfaceAddress());//产品地址
        return "weixin/index";
    }

    @RequestMapping(value = "office", method = GET)
    public String gotoOfficeIndex() throws Exception {
        return "weixin/office-index";
    }

    /**
     * 用户登陆
     */
    @RequestMapping(value = "login")
    public String gotoLoginIndex(Model model, HttpServletRequest request) {
        model.addAttribute("openId", request.getParameter("openId"));
        model.addAttribute("gowhere", request.getParameter("gowhere"));
        return "weixin/WX_Member/wx_login";
//        return "mobile/police/work-mainbmyy";
    }

    /**
     * 进入重新绑定手机页面
     */
    @RequestMapping(value = "rebind")
    public String gotoMobileRebind(Model model) throws Exception {
        model.addAttribute("mobile", DesAPPUtils.decrypt(getWxMemberSession().getMobile()));
        return "weixin/WX_Member/wx_mobile_rebind";
    }

    /**
     * 进入信息绑定页面
     *
     * @return
     */
    @RequestMapping(value = "xxbd")
    public String gotoXxbd(Model model) throws Exception {
        model.addAttribute("mobile", DesAPPUtils.decrypt(getWxMemberSession().getMobile()));
        return "weixin/WX_Member/wx_xxbd";
    }

    /**
     * 车辆信息绑定
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "clxxbd")
    public String gotoClXxbd(Model model) throws Exception {
        model.addAttribute("guid", getWxMemberSession().getGuid());
        String rzResult = memberService.rz(getWxMemberSession().getGuid());
        model.addAttribute("rzResult", rzResult);
        return "weixin/WX_Member/wx_clxxbd";
    }

    /**
     * 驾驶证绑定
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping({"jszbd"})
    public String gotoJszbd(HttpServletRequest request, Model model) throws Exception {

        model.addAttribute("guid", this.getWxMemberSession().getGuid());
//        model.addAttribute("guid","e8354342-0efa-4f4c-8cb0-13248459fbc3");
//        model.addAttribute("member", this.wtMemberService.getWtMemberByUserGuid("e8354342-0efa-4f4c-8cb0-13248459fbc3"));
//        WtMemberMange wtMemberMange = this.weixinQueryService.getWtMemberMange("e8354342-0efa-4f4c-8cb0-13248459fbc3");
        // model.addAttribute("member", this.wtMemberService.getWtMemberByUserGuid(this.getWxMemberSession().getGuid()));
        //获得已经绑定驾驶证和档案编号
        List<DriverInfos> list = driverInfoMapper.loadDriverBindInfo(this.getWxMemberSession().getGuid());
//        List<DriverInfos> list = driverInfoMapper.loadVehicleBindInfo("e8354342-0efa-4f4c-8cb0-13248459fbc3");
        if (list.size() > 0 && null != list) {

            model.addAttribute("diverinfos", list.get(0));
        }
        WtMemberMange wtMemberMange = this.weixinQueryService.getWtMemberMange(this.getWxMemberSession().getGuid());
//        WtMemberMange wtMemberMange = this.weixinQueryService.getWtMemberMange("e8354342-0efa-4f4c-8cb0-13248459fbc3");
        // 获取是否认证信息
        String rzResult = memberService.rz(this.getWxMemberSession().getGuid());
//        String rzResult = memberService.rz("e8354342-0efa-4f4c-8cb0-13248459fbc3");
        model.addAttribute("rzResult", rzResult);
        if (null != wtMemberMange && StringUtils.isNotBlank(wtMemberMange.getTemp5())) {
            model.addAttribute("mange", wtMemberMange.getTemp5());
        } else if (null != wtMemberMange && StringUtils.isBlank(wtMemberMange.getTemp5())) {
            model.addAttribute("mange", "0");
        } else if (null == wtMemberMange) {
            model.addAttribute("rz", "0");
        }

        return "weixin/WX_Member/wx_jszbd";
    }

    /**
     * 进入我的业务界面
     *
     * @return
     */
    @RequestMapping(value = "business")
    public String gotoMyBusiness(HttpServletRequest request, Model model) {
        model.addAttribute("userGuid", request.getParameter("userGuid"));
        return "weixin/WX_Member/wx_mybusiness";
    }

    /**
     * 进入账户信息页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "details")
    public String gotoMemberDetail(HttpServletRequest request, Model model) throws Exception {
        String userGuid = request.getParameter("userGuid");
        WtMember member = super.getMemberByGUid(userGuid);//重新获取
        // 获取是否认证信息
        String rzResult = request.getParameter("rzResult");

        String identifystatus = member.getIdentifystatus();
        Date authTime = member.getCsny();
        if (!Objects.equals("1", rzResult)) {
            rzResult = identifystatus;
        }
        model.addAttribute("rzResult", rzResult);
        model.addAttribute("userGuid", userGuid);// userGuid
        model.addAttribute("loginUser", member);
        return "weixin/WX_Member/wx_member_details";
    }

    /**
     * 进入忘记密码
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "fp")
    public String gotoForgetPasswordIndex(Model model, HttpServletRequest request) {
        model.addAttribute("gowhere", request.getParameter("gowhere"));
        model.addAttribute("openId", request.getParameter("openId"));
        return "weixin/WX_Member/wx_forget_password";
    }

    /**
     * 用户注册协议
     */
    @RequestMapping(value = "register_protocol", method = RequestMethod.GET)
    public String gotoRegister_protocolIndex(HttpServletRequest request, Model model) {
        model.addAttribute("openId", request.getParameter("openId"));
        model.addAttribute("gowhere", request.getParameter("gowhere"));
        return "weixin/WX_Member/wx_register_protocol";
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "register")
    public String gotoRegisterIndex(HttpServletRequest request, Model model) {
        model.addAttribute("openId", request.getParameter("openId"));
        model.addAttribute("gowhere", request.getParameter("gowhere"));
        return "weixin/WX_Member/wx_register";
    }

    /**
     * 开锁业名录查询
     * @param model
     * @return
     */
    @RequestMapping(value = "lock")
    public String  gotoLockIndex(Model model){
        Result r = this.getRegion("370600");
        model.addAttribute("region", r);//获取烟台市区域信息
        return "weixin/WX_Member/wx_ksygs";
    }

    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "entry")
    public String  gotoEntryIndex(Model model){
        return "weixin/WX_Member/wx_crjbljd";
    }

    @ResponseBody
    @RequestMapping(value = "lockDetail",method = GET)
    public Result gotoLockDetail(Model model,HttpServletRequest request){
        String name=request.getParameter("name");
        String address= request.getParameter("address");
        String pi= request.getParameter("pi");
        if(null==pi||"".equals(pi)){
            pi="1";
        }
        String res="";
        try {
            res= HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress()+"/querys/lockList?ps=10&pi="+pi+"&firmname="+name+"&area="+address);
//            res=HttpClientUtil.doGet("http://172.17.100.132:9005/querys/lockList?ps=10&pi="+pi+"&firmname="+name+"&area="+address);
            JSONObject object = JSON.parseObject(res);
            ApiPager apiPager = JSON.parseObject(object.getString("data"), ApiPager.class);

            return new Result(Result.SUCC,apiPager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(Result.FAILURE);
    }
    /**
     * 用户注册
     */
    @RequestMapping(value = "forget_password")
    public String forget_passwordIndex(Model model) {
        return "weixin/WX_Member/wx_forget_password";
    }

    @RequestMapping(value = "details/{infoType}", method = GET)
    public String gotoDetails(@PathVariable("infoType") String infoType) {
        if (infoType.equals("1")) {
            return "weixin/searchLost/lost_details";
        } else if (infoType.equals("2")) {
            return "weixin/searchLost/found_details";
        }
        return null;
    }

    /**
     * 办事查询首页
     * q全部的咨询信息
     */
    @RequestMapping("bszx/index")
    public String gotoLoginIndex(HttpServletRequest request, Model model) {
//        model.addAttribute("member", getWxMemberSession());
        model.addAttribute("pt", request.getParameter("pt"));
        return "weixin/bszx/Homepage";
    }

    @RequestMapping("bszx/myindex")
    public String gotoMyZxIndex(String userGuid, HttpServletRequest request, Model model) {
        WtMember member = getWxMemberSession();
        member = Objects.isNull(member) ? getMemberByGUid(userGuid) : member;
        model.addAttribute("member", member);
        model.addAttribute("userGuid", userGuid);
        model.addAttribute("pt", request.getParameter("pt"));
        return "weixin/bszx/MyZxpage";
    }

    @RequestMapping("myJzxx")
    public String gotoMyJzxx(HttpServletRequest request, Model model) {
        model.addAttribute("userGuid", request.getParameter("userGuid").toString());
        return "weixin/order/myJzxx";
    }

    @RequestMapping("bsjb/myindex")
    public String gotoMyJbIndex(HttpServletRequest request, Model model) {
        // 微信端
        if(  "W".equals(request.getParameter("pt"))) {
            model.addAttribute("pt",request.getParameter("pt"));
            model.addAttribute("member", getWxMemberSession());
            return "weixin/bszx/MyJbpage";
        }else{     // APP端
            model.addAttribute("pt",request.getParameter("pt"));
            model.addAttribute("aUserGuid",request.getParameter("userguid"));
            return "weixin/bszx/MyJbpage";
        }
    }

    /**
     * 我的线索举报详情
     */
    @RequestMapping(value = "jbdetails/{guid}", method = RequestMethod.GET)
    public String gotojbDetails(@PathVariable("guid")String guid, Model model, HttpServletRequest request) {
        model.addAttribute("guid",guid);
        return "weixin/bszx/myjb_details";
    }



    /** APP 、微信 跳转第三方接口  app端传送 guid  微信不传
     * 101004 交通违章处理缴费   101005 驾驶证违法缴费 101006 缴费进度查询
     * @param request pt=W 微信、pt=A APP
     * @param response
     */
    @RequestMapping(value = "get_url",method = RequestMethod.GET)
    public void gotowfIndex(HttpServletRequest request,HttpServletResponse response) {
        String pt = request.getParameter("pt");
        String sfzmhm = "";
        String transacCode = request.getParameter("transacCode");
        String sjhm = "";
        String xm = "";
        if ("W".equals(pt)) {
            //未认证跳转个人中心 实名认证
            // TODO 未提示 直接跳转  合适？
            if (null == getWxMemberSession()) {
                try {
                    response.sendRedirect(HOST + "/percenter/oauth?t=" + Math.abs(new Random().nextInt()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
         else  if (!"1".equals(getWxMemberSession().getIdentifystatus())) {
                try {
                    response.sendRedirect(HOST + "/percenter/oauth?t=" + Math.abs(new Random().nextInt()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }  else {
                xm = getWxMemberSession().getUserName();
                sjhm = getWxMemberSession().getTelephone();
                sfzmhm = getWxMemberSession().getUserCode();
                sfzmhm = DESUtil.encrypt(sfzmhm);
                Map<String, String> param = new HashMap<>();
                param.put("xm", xm);
                param.put("sjhm", sjhm);
                param.put("sfzmhm", sfzmhm);
                param.put("transacCode", transacCode);
                String res = HttpClientUtil.doPostString(configInfo.getServiceInterfaceAddress() + "/member/police/target-pay-url", param);
                JSONObject object = JSON.parseObject(res);
                Result result = JSONObject.parseObject(object.getString("data"), Result.class);
                String url = "";
                if (result.isSucc()) {
                    url = result.getMsg();
                }

//        String url="http://119.164.215.58:9876/h5-webapp/index/toIndex.do?sitecode=XXXX&sreqData =XXXX&signature=XXX&transacCode=XXX";
                try {
                    response.sendRedirect(url);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } else if ("A".equals(pt)) {
//                String guid="a91c5bfcc76a4c15a35ae9a6593dd126";
            String guid = request.getParameter("guid");
            String resu = "";
            try {
                resu = HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress() + "/member/" + guid);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonobject = JSON.parseObject(resu);
            WtMember wtMember = JSON.parseObject(jsonobject.getString("data"), WtMember.class);
            xm = wtMember.getRealname();
            sjhm = wtMember.getTelephone();
            sfzmhm = wtMember.getIdNum();
            sfzmhm = DESUtil.encrypt(sfzmhm);
            Map<String, String> param = new HashMap<>();
            param.put("xm", xm);
            param.put("sjhm", sjhm);
            param.put("sfzmhm", sfzmhm);
            param.put("transacCode", transacCode);
            String res = HttpClientUtil.doPostString(configInfo.getServiceInterfaceAddress() + "/member/police/target-pay-url", param);
            JSONObject object = JSON.parseObject(res);
            Result result = JSONObject.parseObject(object.getString("data"), Result.class);
            String url = "";
            if (result.isSucc()) {
                url = result.getMsg();
            }

//        String url="http://119.164.215.58:9876/h5-webapp/index/toIndex.do?sitecode=XXXX&sreqData =XXXX&signature=XXX&transacCode=XXX";
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    /**
     * 进入QQ实名认证
     */
    @RequestMapping(value = "memberAuth")
    public void gotoQQmemberAuth(HttpServletResponse response,HttpServletRequest request){
      String guid= request.getParameter("userGuid");
        String url="http://ynwx.yungov.cn/api/member/tencent/confirm?userGuid="+guid;
        try {
            response.sendRedirect(url);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }

    @RequestMapping(value = "confirmbackTest", method = GET)
    public void getConfirmBackTest(HttpServletRequest req,HttpServletResponse response,Model model) throws IOException {
        response.getWriter().write(req.getParameter("token"));
    }

    /**
     * 腾讯回调接口
     * @param req
     * @param response
     */
    @RequestMapping(value = "confirmback", method = GET)
    public String getConfirmBack(HttpServletRequest req,HttpServletResponse response,Model model)
    {
        //TX回调返回数据
        String token=req.getParameter("token");
        String uid =req.getParameter("uid");
        String errorcode = req.getParameter("errorcode");

        if("0".equals(errorcode)){


        log.error("++++++++++++++++++++++++++++++++++++++++++++++++TX back+++++++++++++++++++++++++++++++++++++++++++++++++++++");

        String res="";
        try {
            //调用接口返回用户信息
            res=  HttpClientUtil.doPostString(configInfo.getServiceInterfaceAddress()+"/member/tencent/info",new HashMap<String,String>(){
                {
//                    put("token", "{7FE24096-56CF-4353-9DAB-F72F5C291FAC}");
//                    put("userGuid", "7fd94ae17ad04d4f91b9b4365d9b7a45");
                    put("token", token);
                    put("userGuid", uid);
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        JSONObject jsonObject = JSON.parseObject(res);
        WtMember member = UserInfoUtil.getWtMember(jsonObject.getString("data"));
        this.saveWxMemberSession(member);

        String identifystatus = member.getIdentifystatus();

        model.addAttribute("rzResult", identifystatus);
        model.addAttribute("userGuid", uid);// userGuid
        model.addAttribute("loginUser", member);

        }
        return "weixin/WX_Member/wx_member_details";
    }


}
